﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
using Facebook_Graph_Toolkit;
using JSON;
using Facebook_Graph_Toolkit.GraphApi;
using System.Collections;


public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        this.ClientScript.GetPostBackEventReference(this, "arg");

        if (!IsPostBack)
        {
            getStateList();

            if (Request["code"] != null)
            {
                setControlValues();
            }

            if (Request.QueryString["EditListingId"] != null)
            {
                fillControlValues();
            }
        }
        string eventTarget = this.Request["__EVENTTARGET"];
        string eventArgument = this.Request["__EVENTARGUMENT"];

        if (eventTarget != String.Empty && eventTarget == "callPostBack" && eventArgument == "btnPostClick")
        {
            if (Request.QueryString["EditListingId"] == null)
            {
                SaveProfileInformation();
            }
            else if (Request.QueryString["EditListingId"] != null)
            {
                updateListingInformation();
            }
        }

    }

    private void fillControlValues()
    {
        int listingId = Convert.ToInt32(Request.QueryString["EditListingId"].ToString());

        DataTable dtListing = new DataTable();
        dtListing = BuddyAgentDAL.GetParticularListingInfo(Convert.ToInt32(Request.QueryString["EditListingId"].ToString()));

        DataTable dtAgentProfile = new DataTable();
        dtAgentProfile = BuddyAgentDAL.GetBuddyAgentInfo(Convert.ToInt32(dtListing.Rows[0][1]));


        DataTable dtCurrentPreviousListing = new DataTable();
        dtCurrentPreviousListing = BuddyAgentDAL.GetCurrentPreviousListing(Convert.ToInt32(dtListing.Rows[0][1]));

        lblActiveListingCount.Text = "(" + dtCurrentPreviousListing.Rows[0][1].ToString() + ")";
        lblPreviousListingCount.Text = "(" + dtCurrentPreviousListing.Rows[0][2].ToString() + ")";

        DataSet dsAgentInformation = new DataSet();
        dsAgentInformation = BuddyAgentDAL.GetBuddyAgentInfoBasedOnFBId(dtAgentProfile.Rows[0][3].ToString());

        imgUsr.ImageUrl = dsAgentInformation.Tables[0].Rows[0][2].ToString();
        lblProfileMsg.Text = dsAgentInformation.Tables[0].Rows[0][1].ToString() + ".<br/><br/>";

        if (dsAgentInformation.Tables[0].Rows.Count != 0)
        {
            DateTime dt = DateTime.Parse(dsAgentInformation.Tables[0].Rows[0][5].ToString());

            lblProfileMes.Text = "Member Since " + dt.Year;
            lblFriends.Text = "I have " + dsAgentInformation.Tables[1].Rows[0][0].ToString() + " Friends.<br/>";
            lblProfileMes.Visible = true;
            lblFriends.Visible = true;
        }

        DataTable dtListingInfo = new DataTable();
        dtListingInfo = BuddyAgentDAL.GetParticularListingInfo(listingId);

        txtText.Text = dtListingInfo.Rows[0]["ListingHeader"].ToString();
        txtPrice.Text = dtListingInfo.Rows[0]["Price"].ToString();
        txtArea.Text = dtListingInfo.Rows[0]["Area"].ToString();


        ddlState.SelectedIndex = -1;
        ddlState.Items.FindByText(dtListingInfo.Rows[0]["State"].ToString()).Selected = true;

        ddlCity.Enabled = true;
        DataTable dtCity = new DataTable();
        dtCity = BuddyAgentDAL.GetCitiesBasedOnState(ddlState.SelectedItem.Text.ToString());
        ddlCity.Items.Clear();
        ddlCity.Items.Add(new ListItem("Select City"));
        for (int i = 0; i < dtCity.Rows.Count; i++)
            ddlCity.Items.Add(new ListItem(dtCity.Rows[i][0].ToString()));

        ddlCity.SelectedIndex = -1;
        ddlCity.Items.FindByText(dtListingInfo.Rows[0]["City"].ToString()).Selected = true;
        ddlCity.Enabled = true;


        ddlCategorey.SelectedIndex = -1;
        ddlCategorey.Items.FindByText(dtListingInfo.Rows[0]["ListingCategorey"].ToString()).Selected = true;
        ddlSubCategorey.Enabled = true;

        ddlSubCategorey.SelectedIndex = -1;
        ddlSubCategorey.Items.FindByText(dtListingInfo.Rows[0]["ListingSubCategorey"].ToString()).Selected = true;
        if (dtListingInfo.Rows[0]["ListingSubCategorey"].ToString().ToLower() == "commercial")
        {
            ddlSecSubCategorey.Enabled = true;
            ddlSecSubCategorey.SelectedIndex = -1;
            ddlSecSubCategorey.Items.FindByText(dtListingInfo.Rows[0]["ListingSecSubCategorey"].ToString()).Selected = true;
        }

        txtWhy.Text = dtListingInfo.Rows[0]["ReasonOfListing"].ToString();
        txtDesc.Text = dtListingInfo.Rows[0]["Description"].ToString();
        txtBedroom.Text = dtListingInfo.Rows[0]["NoOfBedrooms"].ToString();
        txtBathroom.Text = dtListingInfo.Rows[0]["NoOfBathrooms"].ToString();
        txtSqfeet.Text = dtListingInfo.Rows[0]["SqFeets"].ToString();

        ddlCarParking.SelectedIndex = -1;
        ddlCarParking.Items.FindByText(dtListingInfo.Rows[0]["CarParking"].ToString()).Selected = true;

        ddlPets.SelectedIndex = -1;
        ddlPets.Items.FindByText(dtListingInfo.Rows[0]["PetsAllowed"].ToString()).Selected = true;

        ddlWatchman.SelectedIndex = -1;
        ddlWatchman.Items.FindByText(dtListingInfo.Rows[0]["Watchman"].ToString()).Selected = true;

        txtAddress.Text = dtListingInfo.Rows[0]["Address"].ToString();

        if (dtListingInfo.Rows[0]["ShowAddress"].ToString() == "1")
            chkShowAddress.Checked = true;
        else if (dtListingInfo.Rows[0]["ShowAddress"].ToString() == "0")
            chkShowAddress.Checked = false;
        txtPhoneNo.Text = dtListingInfo.Rows[0]["PhoneNo"].ToString();

        if (dtListingInfo.Rows[0]["FriendsOnly"].ToString() == "1")
            chkFriend.Checked = true;
        else if (dtListingInfo.Rows[0]["FriendsOnly"].ToString() == "0")
            chkFriend.Checked = false;
        if (ddlSecSubCategorey.Enabled == true)
        {
            txtBedroom.Enabled = false;
            ddlPets.Enabled = false;
        }
        else
        {
            txtBedroom.Enabled = true;
            ddlPets.Enabled = true;
        }
    }

    private void SaveProfileInformation()
    {

        #region SaveProfileInformationInDB
        string fullName, facebookId, email, photoPath = "", friendId, friendName;

        oAuthFacebook oAuth = new oAuthFacebook();

        if (Request["code"] == null)
        {

            oAuth.AccessTokenGet(Request["code"]);

        }
        else
        {
            try
            {
                oAuth.AccessTokenGet(Request["code"]);
                Api api = new Api(oAuth.Token);
                User u = api.GetUser();

                facebookId = api.UserID;
                fullName = u.first_name + " " + u.last_name;
                email = u.email;
                photoPath = api.GetPictureURL(u.id);

                //IList album = (IList)u.GetAlbums(oAuth.Token);
                //foreach (Facebook_Graph_Toolkit.GraphApi.Album li in album)
                //{
                //    if (li.name == "Profile Pictures")
                //    {
                //        IList photos = (IList)li.GetPhotos(oAuth.Token);

                //        foreach (Facebook_Graph_Toolkit.GraphApi.Photo list in photos)
                //        {
                //            photoPath = list.picture;
                //            break;
                //        }
                //    }
                //}

                DataTable dtProfileAgentId = new DataTable();
                dtProfileAgentId = BuddyAgentDAL.SetBuddyAgentInformation(fullName, photoPath, facebookId, email);
                int agentId = Convert.ToInt32(dtProfileAgentId.Rows[0][0].ToString());

                IList friends = (IList)api.GetFriends();
                foreach (Facebook_Graph_Toolkit.FacebookObjects.NameIDPair pair in friends)
                {
                    friendId = pair.id;
                    friendName = pair.name;
                    DataSet ds = new DataSet();
                    ds = BuddyAgentDAL.GetBuddyAgentInfoBasedOnFBId(friendId);
                    if (ds.Tables[0].Rows.Count != 0)
                    {
                        string facebookfriendId = ds.Tables[0].Rows[0][3].ToString();
                        int BuddyAgentId = Convert.ToInt32(ds.Tables[0].Rows[0][0].ToString());
                        BuddyAgentDAL.SetBuddyAgentFriendsInfo(agentId, BuddyAgentId, friendId, friendName);
                        BuddyAgentDAL.updateBuddyAgentfriendId(agentId, facebookId);
                    }
                    else
                    {
                        BuddyAgentDAL.SetBuddyAgentFriendsInfo(agentId, -1, friendId, friendName);
                    }
                }
                Post(agentId);
            }
            catch
            {
            }
        }
        #endregion

    }

    private void setControlValues()
    {

        string pictureURL = "";
        ddlCategorey.Attributes.Add("onChange", "javascript:ShowSubCatDdl()");
        ddlSubCategorey.Attributes.Add("onChange", "javascript:ShowSecSubCatDdl()");
        oAuthFacebook oAuth = new oAuthFacebook();

        if (Request["code"] != null)
        {

            try
            {
                oAuth.AccessTokenGet(Request["code"]);
                Api api = new Api(oAuth.Token);
                User u = api.GetUser();
                pictureURL = api.GetPictureURL(u.id);
                hideFBID.Value = u.id;

                //IList album = (IList)u.GetAlbums(oAuth.Token);
                //foreach (Facebook_Graph_Toolkit.GraphApi.Album li in album)
                //{
                //    if (li.name == "Profile Pictures")
                //    {
                //        IList photos = (IList)li.GetPhotos(oAuth.Token);

                //        foreach (Facebook_Graph_Toolkit.GraphApi.Photo list in photos)
                //        {
                //            pictureURL = list.picture;
                //            break;
                //        }
                //    }
                //}

                imgUsr.ImageUrl = pictureURL;
                //imgUsr.ImageUrl = api.GetPictureURL(u.id);
                lblProfileMsg.Text = u.first_name + " " + u.last_name + ".<br/><br/>";


                DataTable dtCurrentPreviousListing = new DataTable();
                dtCurrentPreviousListing = BuddyAgentDAL.GetCurrentPreviousListingBasedOnFB(u.id);

                lblActiveListingCount.Text = "(" + dtCurrentPreviousListing.Rows[0][1].ToString() + ")";
                lblPreviousListingCount.Text = "(" + dtCurrentPreviousListing.Rows[0][2].ToString() + ")";

                DataSet dsAgentInformation = new DataSet();
                dsAgentInformation = BuddyAgentDAL.GetBuddyAgentInfoBasedOnFBId(u.id);

                if (dsAgentInformation.Tables[0].Rows.Count != 0)
                {
                    DateTime dt = DateTime.Parse(dsAgentInformation.Tables[0].Rows[0][5].ToString());

                    lblProfileMes.Text = "Member Since " + dt.Year;
                    lblFriends.Text = "I have " + dsAgentInformation.Tables[1].Rows[0][0].ToString() + " Friends.<br/>";
                    lblProfileMes.Visible = true;
                    lblFriends.Visible = true;
                }
            }
            catch
            {
            }

        }
    }

    private void getStateList()
    {
        DataTable dtStates = new DataTable();
        dtStates = BuddyAgentDAL.GetStates();
        //ddlState.DataTextField = "State";
        //ddlState.DataBind();
        ddlState.Items.Add(new ListItem("Select State"));
        for (int i = 0; i < dtStates.Rows.Count; i++)
            ddlState.Items.Add(new ListItem(dtStates.Rows[i][0].ToString()));
    }

    protected void ddlSubCategorey_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlSubCategorey.SelectedItem.Text == "Commercial")
        {
            ddlSecSubCategorey.Visible = true;
        }
    }

    private void clearAllFields()
    {
        txtText.Text = " What are You Listing?";
        txtPrice.Text = " Price";
        txtPrice.Enabled = true;

        ddlCountry.SelectedIndex = -1;
        ddlState.SelectedIndex = -1;
        ddlCity.SelectedIndex = -1;
        txtArea.Text = " Area";
        ddlCategorey.SelectedIndex = -1;
        ddlSubCategorey.SelectedIndex = -1;
        ddlSecSubCategorey.SelectedIndex = -1;
        txtWhy.Text = "";
        txtDesc.Text = "";
        chkFriend.Checked = false;
        txtBedroom.Text = "";
        txtBathroom.Text = "";
        txtSqfeet.Text = "";
        ddlCarParking.SelectedIndex = -1;
        txtAddress.Text = "";
        ddlPets.SelectedIndex = -1;
        lblMessage.Text = "";
        txtPhoneNo.Text = "";
    }

    private void MakeDirectoryIfNotExists(string NewDirectory)
    {
        try
        {
            // Check if directory exists
            if (!Directory.Exists(NewDirectory))
            {
                // Create the directory.
                Directory.CreateDirectory(NewDirectory);
            }
        }
        catch (IOException _ex)
        {
            Response.Write(_ex.Message);
        }
    }

    private void Post(int agentId)
    {
        #region SavePostInformationInDB
        int friendOnly;
        if (chkFriend.Checked == true)
            friendOnly = 1;
        else
            friendOnly = 0;

        int showAddressInListing;

        if (chkShowAddress.Checked == true)
            showAddressInListing = 1;
        else
            showAddressInListing = 0;

        if (ddlSubCategorey.SelectedItem.Text.ToLower() == "commercial")
        {
            txtBedroom.Text = "0";
            ddlPets.SelectedIndex = 4;
        }

        DataTable dtListingId = new DataTable();
        dtListingId = BuddyAgentDAL.setListingInformation(agentId, txtText.Text, txtPrice.Text, ddlCountry.SelectedItem.Text, ddlState.SelectedItem.Text,
            ddlCity.SelectedItem.Text, txtArea.Text, ddlCategorey.SelectedItem.Text, ddlSubCategorey.SelectedItem.Text,
            ddlSecSubCategorey.SelectedItem.Text, txtWhy.Text, txtDesc.Text, friendOnly, Convert.ToInt32(txtBedroom.Text),
            Convert.ToInt32(txtBathroom.Text), Convert.ToInt32(txtSqfeet.Text), Convert.ToInt32(ddlCarParking.SelectedItem.Text), ddlWatchman.SelectedItem.Text, txtAddress.Text,
            ddlPets.SelectedItem.Text, showAddressInListing, txtPhoneNo.Text);

        clearAllFields();
        lblMessage.Text = "Your Listing Information Inserted Successfully";
        #endregion
        Response.Redirect("~/PostListingInProcess.aspx?ListingId=" + dtListingId.Rows[0][0].ToString());
    }

    private void updateListingInformation()
    {
        #region SavePostInformationInDB
        int friendOnly;
        if (chkFriend.Checked == true)
            friendOnly = 1;
        else
            friendOnly = 0;

        int showAddressInListing;

        if (chkShowAddress.Checked == true)
            showAddressInListing = 1;
        else
            showAddressInListing = 0;

        if (ddlSubCategorey.SelectedItem.Text.ToLower() == "commercial")
        {
            txtBedroom.Text = "0";
            ddlPets.SelectedIndex = 4;
        }

        int listingId = Convert.ToInt32(Request.QueryString["EditListingId"].ToString());

        DataTable dtListing = new DataTable();
        dtListing = BuddyAgentDAL.GetParticularListingInfo(Convert.ToInt32(Request.QueryString["EditListingId"].ToString()));
        int agentId = Convert.ToInt32(dtListing.Rows[0][1]);


        BuddyAgentDAL.updateListingInformation(listingId, agentId, txtText.Text, txtPrice.Text, ddlCountry.SelectedItem.Text, ddlState.SelectedItem.Text,
             ddlCity.SelectedItem.Text, txtArea.Text, ddlCategorey.SelectedItem.Text, ddlSubCategorey.SelectedItem.Text,
             ddlSecSubCategorey.SelectedItem.Text, txtWhy.Text, txtDesc.Text, friendOnly, Convert.ToInt32(txtBedroom.Text),
             Convert.ToInt32(txtBathroom.Text), Convert.ToInt32(txtSqfeet.Text), Convert.ToInt32(ddlCarParking.SelectedItem.Text), ddlWatchman.SelectedItem.Text, txtAddress.Text,
             ddlPets.SelectedItem.Text, showAddressInListing, txtPhoneNo.Text);

        clearAllFields();
        lblMessage.Text = "Your Listing Information Updated Successfully";
        #endregion
        Response.Redirect("~/PostListingInProcess.aspx?EditListingId=" + listingId.ToString());
    }

    public static void Copy(string sourceDirectory, string targetDirectory)
    {
        DirectoryInfo diSource = new DirectoryInfo(sourceDirectory);
        DirectoryInfo diTarget = new DirectoryInfo(targetDirectory);
        moveAllFromTemp(diSource, diTarget);
    }

    public static void moveAllFromTemp(DirectoryInfo source, DirectoryInfo target)
    {

        if (Directory.Exists(target.FullName) == false)
        {
            Directory.CreateDirectory(target.FullName);
        }

        foreach (FileInfo fi in source.GetFiles())
        {
            fi.MoveTo(Path.Combine(target.ToString(), fi.Name));
        }
        // Copy each subdirectory using recursion.
        //foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
        //{
        //    DirectoryInfo nextTargetSubDir =
        //    target.CreateSubdirectory(diSourceSubDir.Name);
        //    CopyAll(diSourceSubDir, nextTargetSubDir);
        //}
    }

    protected void btnClear_Click(object sender, EventArgs e)
    {
        clearAllFields();
    }

    protected void linkViewProfile_Click(object sender, EventArgs e)
    {
        oAuthFacebook oAuth = new oAuthFacebook();
        oAuth.AccessTokenGet(Request["code"]);

        if (Request["code"] != null)
        {
            Api api = new Api(oAuth.Token);
            User u = api.GetUser();
            Response.Redirect(u.link);
        }
    }

    protected void linkActiveListing_Click(object sender, EventArgs e)
    {
        if (lblActiveListingCount.Text != "")
        {
            DataSet dsAgent = new DataSet();
            dsAgent = BuddyAgentDAL.GetBuddyAgentInfoBasedOnFBId(hideFBID.Value);
            string clientId = dsAgent.Tables[0].Rows[0][0].ToString();
            Response.Redirect("~/Default.aspx?ClientId=" + clientId + "&Active=1");
        }
    }

    protected void linkPreviousListing_Click(object sender, EventArgs e)
    {
        if (lblPreviousListingCount.Text != "")
        {
            DataSet dsAgent = new DataSet();
            dsAgent = BuddyAgentDAL.GetBuddyAgentInfoBasedOnFBId(hideFBID.Value);
            string clientId = dsAgent.Tables[0].Rows[0][0].ToString();
            Response.Redirect("~/Default.aspx?ClientId=" + clientId + "&Active=-1");
        }
    }

    protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
    {
        ddlCity.Enabled = true;
        DataTable dtCity = new DataTable();
        dtCity = BuddyAgentDAL.GetCitiesBasedOnState(ddlState.SelectedItem.Text.ToString());
        //ddlState.DataTextField = "City";
        //ddlState.DataBind();
        ddlCity.Items.Clear();
        ddlCity.Items.Add(new ListItem("Select City"));
        for (int i = 0; i < dtCity.Rows.Count; i++)
            ddlCity.Items.Add(new ListItem(dtCity.Rows[i][0].ToString()));

    }
}